trigger setmanagerforhospital on Hospital__c (after update,before insert) {
    list<id> idl=new list<id>();
    list<Hospital__c> hosl=new list<Hospital__c>();
    list<user> u=new list<user>();
    list<id> uid=new list<id>();
    
    boolean b=false;
     for(Hospital__c h:trigger.new){
         uid.add(h.ownerid);
     }
    
    for(hospital__c hos:trigger.new){
    if(system.trigger.isupdate){
        if(system.trigger.oldmap.get(hos.id).ownerid != hos.ownerid){
            idl.add(hos.id);
            b=true;
        }
       }else if(system.trigger.isinsert){
           b=true;
       }
    }
     
    if(b){
    u=[select id,managerid from user where id in:uid];
    }
    
    if(system.trigger.isupdate && b ){
    list<hospital__c> hospitalList=[select manager__c,id,OwnerId from hospital__c where id in:idl];
    for(Hospital__c ht:hospitalList){
        if(system.trigger.oldmap.get(ht.id).ownerid != ht.ownerid){
                for(user ul:u){
                    if(ul.id==ht.ownerid){
                        ht.manager__c=ul.managerid;
                    }
              }  
            }
        }
        update hospitalList;
    }else if(system.trigger.isinsert ){
        for(Hospital__c ht:trigger.new){
                for(user ul:u){
                    if(ul.id==ht.ownerid){
                       ht.manager__c=ul.managerid;
                    }
                }
              }  
            }
    









/*
for(hospital__c hp:trigger.new){
        if(system.trigger.isupdate){
            if(system.trigger.oldmap.get(hp.id).ownerid != hp.ownerid){
                user u=[select id,managerid from user where id=: hp.OwnerId];
                hospital__c hl=[select id,manager__c from hospital__c where id=:hp.id];
                    if(u.managerid<>null){
                        hospital__c h=hl;
                        h.manager__c=u.managerid;
                        update h;
                        }
                    }
             }else
              if(system.trigger.isinsert){
                     user u=[select id,managerid from user where id=: hp.OwnerId];
                hospital__c hl=[select id,manager__c from hospital__c where id=:hp.id];
                    if(u.managerid<>null){
                        hospital__c h=hl;
                        h.manager__c=u.managerid;
                        update h;
                        }
             }
        }*/
}